const dotenv = require('dotenv');
const result = dotenv.config();
if (result.error) {
    throw result.error;
}
const retry = require('bluebird-retry');
const retryPromise = require('bluebird');
const config = require('./config');
const MetamonApi = require('./metamon_api');
const Web3 = require('web3');

let wait = ms => new Promise(resolve => setTimeout(resolve, ms));


async function run(config) {
    console.log("=====================程序开始执行==========================");
    try {
        let metamonApi = new MetamonApi(config.address, config.chain, config.privateKey);
        

        if(config.accessToken) {
            metamonApi.setAccessToken(config.accessToken);
        } else {
            /// 程序登录，设置accessToken
            let accessToken =  await metamonApi.login();
            metamonApi.setAccessToken(accessToken);
        }

        ///查询背包
        let nfts = await metamonApi.checkBag();
        let eggs;
        for (let i=0; i<nfts.length; i++) {
            let item = nfts[i];
            if (item.bpType == 6) {
                eggs = item;
                break;
            }
        }
        
        if(eggs && eggs.bpNum > 0) {
            console.log("您的账号当前拥有"+eggs.bpNum+"个蛋，准备开蛋！");
            let successCount = 0;
            let failCount = 0;
            for(let j=0; j<eggs.bpNum; j++) {
                try {
                    let result = await metamonApi.openEgg();
                    let data = result.data;
                    if (!data) {
                        console.log("第"+(j+1)+"个开蛋失败, 返回数据为空：" + result);
                        continue;
                    }
                    console.log("第"+(j+1)+"个开蛋成功，获得物品：" + data.category+"，数量："+data.amount);
                    successCount++;
                    
                } catch(e) {
                    console.log("第"+(j+1)+"个开蛋失败: " + e);
                    failCount++;
                }
                await wait(3000);
            }
            console.log("开蛋结束，累积成功"+successCount+"次，失败"+failCount+"次");

        } else {
            console.log("您的账号没有蛋可开！");
        }
    } catch (e) {

    }

}


run(config);